/**
 * Project Name:template-web
 * File Name   :ServletUtil.java
 * Package Name:org.cn.template.component.utils
 * Date:2015年9月27日下午4:16:05
 * Copyright (c) 2015, http://my.oschina.net/httpssl All Rights Reserved.
 *
*/

package org.cn.template.component.utils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.cn.template.component.domain.User;
import org.cn.template.component.page.PagerUtil;
import org.cn.template.component.web.UrlTag;

/**
 * ClassName:ServletUtil <br/>
 * Function :TODO ADD FUNCTION. <br/>
 * Reason	:TODO ADD REASON. <br/>
 * Date     :2015年9月27日 下午4:16:05 <br/>
 * @author  :http://my.oschina.net/httpssl
 * @email   :491835898@QQ.COM
 * @since   :JDK 1.7
 * @see 	 
 */
public class ServletUtil
{
	public final static String		COOKIE_LOGIN	= "admin_id";
	private final static int	MAX_AGE			= 86400 * 365;
	private final static byte[]	E_KEY			= new byte[] { '1', '2', '3', '4', '5', '6', '7', '8' };
	private final static String	UTF_8			= "UTF-8";
	
	public static final String BASE_TEMPLATE_PATH_ADMIN = "/admin";
	
	private static String[]prefix = {"http://","https://"};
	private static String[]suffix = UrlTag.suffix;
	public static String getURI_with_suffix(String uri,int type){
		return uri+suffix[type];
	}
	public static String getURI_with_suffix(String uri){
		return getURI_with_suffix(uri,0);
	}
	public static String getHttpUrl(int type,String url){
		return prefix[type]+url;
	}
	/*
	 * http://
	 */
	public static String getHttpUrl(String url){
		return getHttpUrl(0,url);
	}
	
	public static User checkLoginStatusCookie(HttpServletRequest req) {
		Cookie cookie = CookieUtil.getCookieByName(req, COOKIE_LOGIN);
		if (cookie != null && StringUtils.isNoneEmpty(cookie.getValue())) {
			return adminFromCookie(req,cookie.getValue());
		}
		return null;
	}
	
	/**
     * 生成用户登录标识字符串
     * @param user
     * @param ip
     * @param user_agent
     * @return
     */
    public static String genLoginKey(User user, String ip, String user_agent) {
        StringBuilder sb = new StringBuilder();
        sb.append(user.getId());
        sb.append('|');
        sb.append(user.getLoginName());
        sb.append('|');
        sb.append(user.getPassword());
        sb.append('|');
        sb.append(ip);
        sb.append('|');
        sb.append((user_agent==null)?0:user_agent.hashCode());
        sb.append('|');
        sb.append(System.currentTimeMillis());
        return _Encrypt(sb.toString()); 
    }
    
    /**
     * 加密
     * @param value
     * @return 
     * @throws Exception 
     */
    private static String _Encrypt(String value) {
        byte[] data = CryptUtil.encrypt(value.getBytes(), E_KEY);
        try{
            return URLEncoder.encode(new String(Base64.encodeBase64(data)), UTF_8);
        }catch(UnsupportedEncodingException e){
            return null;
        }
    }
	/**
	 * 解密
	 * 
	 * @param value
	 * @return
	 * @throws Exception
	 */
	private static String _Decrypt(String value) {
		try {
			value = URLDecoder.decode(value, UTF_8);
			if (StringUtils.isBlank(value))
				return null;
			byte[] data = Base64.decodeBase64(value.getBytes());
			return new String(CryptUtil.decrypt(data, E_KEY));
		} catch (UnsupportedEncodingException excp) {
			return null;
		}
	}

	/**
	 * 从cookie中读取保存的用户信息
	 * 
	 * @param req
	 * @return
	 */
	public static User adminFromCookie(HttpServletRequest req, String uuid) {
		if (StringUtils.isBlank(uuid))
			return null;
		String ck = _Decrypt(uuid);
		final String[] items = StringUtils.split(ck, '|');
		if (items.length == 6) {
			String ua = header(req, "user-agent");
			int ua_code = (ua == null) ? 0 : ua.hashCode();
			int old_ua_code = Integer.parseInt(items[4]);
			if (ua_code == old_ua_code) {
				return new User(NumberUtils.toLong(items[0], -1L),items[1], items[2]);
			}
		}
		return null;
	}

	private static String header(HttpServletRequest req, String string) {
		return req.getHeader(string);
	}
	
	/**
     * 保存登录信息
     * @param req
     * @param res
     * @param user
     * @param save
     */
    public static void saveUserInCookie(HttpServletRequest request,HttpServletResponse response,User user) {
        String new_value = genLoginKey(user,RequestUtil.getRemoteAddr(request),header(request,"user-agent"));
        RequestUtil.deleteCookie(request, response,COOKIE_LOGIN,true);
        RequestUtil.setCookie(request, response,COOKIE_LOGIN,new_value,MAX_AGE);
    }
 
    public static void deleteUserInCookie(HttpServletRequest request,HttpServletResponse response) {
    	RequestUtil.deleteCookie(request, response,COOKIE_LOGIN,true);
    }
    
	/**
	 * 获取请求的参数，包含分页参数的初始化
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getPageParameterMap(HttpServletRequest request)
	{
		Map<String, Object> parameterMap = getParameterMap(request);
		return getPageParameterMap(parameterMap);
	}

	/**
	 * 获取分页参数
	 * 
	 * @param request
	 * @param page
	 *            页码
	 * @param rows
	 *            每页数据量的大小
	 * @return
	 */
	public static Map<String, Object> getPageParameterMap(HttpServletRequest request, String page, String rows)
	{
		Map<String, Object> parameterMap = getParameterMap(request);
		parameterMap.put("page", page);
		parameterMap.put("rows", rows);
		return getPageParameterMap(parameterMap);
	}

	/**
	 * 获取请求的参数，包含分页参数的初始化
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getPageParameterMap(Map<String, Object> parameterMap)
	{
		// 当前页码
		String page = parameterMap.containsKey("page") ? parameterMap.get("page").toString() : null;
		// 每页显示数量
		String rows = parameterMap.containsKey("rows") ? parameterMap.get("rows").toString() : null;
		if (StringUtils.isNotEmpty(page) && NumberUtils.isNumber(page)) {
			int pg = Integer.valueOf(page);
			if (pg > 0) {
				parameterMap.put("page", Integer.valueOf(page));
			} else {
				parameterMap.put("page", 1);
			}
		} else {
			parameterMap.put("page", 1);
		}
		if (StringUtils.isNotEmpty(rows) && NumberUtils.isNumber(rows)) {
			int rs = Integer.valueOf(rows);
			if (rs >= 1 && rs <= PagerUtil.defaultPageRows) {
				parameterMap.put("rows", rs);
			}
		} else {
			parameterMap.put("rows", PagerUtil.defaultPageRows);
		}
		return parameterMap;
	}

	/**
	 * 获取request中参数的集合,如果有多个值的对于只取其中一个
	 * 
	 * @return
	 */
	public static Map<String, Object> getParameterMap(HttpServletRequest request)
	{
		return getParameterMap(request, false);
	}

	/**
	 * 获取request中参数集合，如果有多个值的，获取的是数组
	 * 
	 * @param request
	 * @param isParams
	 *            多个值的是否是数组
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getParameterMap(HttpServletRequest request, boolean isParams)
	{
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		Map<String, Object> paramMap = request.getParameterMap();
		for (Iterator<String> iter = paramMap.keySet().iterator(); iter.hasNext();) {
			String key = iter.next();
			Object value = null;
			Object obj = paramMap.get(key);
			if (isParams) {
				value = obj;
			} else {
				if ((obj.getClass().isArray()) && Array.getLength(obj) >= 1) {
					value = Array.get(obj, 0);
				}
			}
			if (value != null) {
				if (value.getClass().isArray()) {
					int len = Array.getLength(value);
					for (int i = 0; i < len; i++) {
						Object temp = Array.get(value, i);
						Array.set(value, i, temp != null ? temp.toString().trim() : null);
					}
				} else {
					value = value != null ? value.toString().trim() : null;
				}
			}
			parameterMap.put(key, value);
		}
		return parameterMap;
	}
	
}
